from flask import (Blueprint, request, abort)
from db import DBSession, Author
from utils import normalizeRes
import datetime

bp = Blueprint('author', __name__, url_prefix='/api/system/author')


# 创建权限
@bp.route('/create', methods=['POST'])
def create_author():
    try:
        session = DBSession()
        # if not request.json['parentId']:
        #     abort(400)
        if not request.json['name']:
            abort(400)
        if not request.json['url']:
            abort(400)
        if not request.json['code']:
            abort(400)
        new_author = Author(
            name=request.json['name'],
            parent_id=request.json['parentId'],
            code=request.json['code'],
            url=request.json['url'],
            is_menu=request.json['isMenu'],
            is_effective=request.json.get('isEffective'),
            editor=request.json.get('editor'),
            operate=','.join(map(lambda x: str(x), request.json.get('actions')))
        )
        session.add(new_author)
        session.commit()
        return normalizeRes({
            'author': request.json
        })
    except Exception as e:
        print(e)
        return normalizeRes(None, message=e, success=False)
    finally:
        session.close()


# 获取权限列表
@bp.route('/list', methods=['GET'])
def get_authors():
    try:
        session = DBSession()
        authors = session.query(Author).filter(Author.is_effective).all()
        authorList = []
        for author in authors:
            authorList.append({
                'id': author.id,
                'name': author.name,
                'parent_id': author.parent_id
            })
        return normalizeRes(authorList)
    except Exception as e:
        print(e)
    finally:
        session.close()


# 获取权限详情
@bp.route('/<int:authorId>', methods=['GET'])
def get_detail(authorId):
    session = DBSession()
    author = session.query(Author).filter_by(id=authorId).one()
    session.close()
    return normalizeRes({
        'id': author.id,
        'name': author.name,
        'isMenu': author.is_menu,
        'url': author.url,
        'code': author.code,
        'isEffective': author.is_effective,
        'actions': author.operate.split(','),
        'editor': author.editor,
        'editTime': author.edit_time
    })


# 修改权限
@bp.route('/<int:authorId>', methods=['PUT'])
def update_detail(authorId):
    session = DBSession()
    new_author = request.json
    print('isEffective:', new_author.get('isEffective'), ' ,menu:', new_author.get('isMenu'))
    author = session.query(Author).filter_by(id=authorId).one()
    author.name = new_author.get('name', author.name),
    # author.is_menu = new_author.get('isMenu'),
    author.url = new_author.get('url', author.url),
    author.code = new_author.get('code', author.code),
    # author.is_effective = new_author.get('isEffective'),
    author.operate = ','.join(map(lambda x: str(x), new_author.get('actions'))),
    author.editor = new_author.get('editor', author.editor),
    session.commit()
    session.close()
    return get_detail(authorId)


# 删除权限
@bp.route('/<int:authorId>', methods=['DELETE'])
def delete_author(authorId):
    session = DBSession()
    author = session.query(Author).filter(Author.id == authorId).one()
    author.is_effective = False
    session.commit()
    session.close()
    return get_detail(authorId)

